import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";

import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, hideTextAtIndex } from "@pureadmin/utils";
import { getUserList, updateUserInfo, getAllRoleList } from "@/api/system";
import { ElMessageBox } from "element-plus";
import { h, ref, toRaw, computed, reactive, onMounted } from "vue";

export function useUser(tableRef, treeRef) {
  const form = reactive({
    nickname: "",
    phone: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const loading = ref(true);
  // 上传头像信息
  const selectedNum = ref(0);
  const pagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1
  });
  const columns = [
    {
      label: "用户编号",
      prop: "id",
      width: 90
    },
    {
      label: "用户头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.headimgurl}
          preview-src-list={Array.of(row.avatar || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "性别",
      prop: "sex",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.sex === "1" ? "danger" : null}
          effect="plain"
        >
          {row.sex === "1" ? "女" : "男"}
        </el-tag>
      )
    },
    {
      label: "手机号码",
      prop: "phone",
      minWidth: 90
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  const roleOptions = ref([]);

  function handleSizeChange(val) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  async function onSearch() {
    loading.value = true;
    let param = toRaw({ ...form, ...pagination });
    const { data } = await getUserList(param);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.nickname
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );

        updateUserInfo({ id: row.id, status: row.status ? 1 : 0 })
          .then(() => {
            onSearch();
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
            message("已成功修改用户状态", {
              type: "success"
            });
          })
          .catch(() => {
            message("用户状态修改失败", {
              type: "success"
            });
          });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function openDialog(title = "", row) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          id: row?.id ?? "",
          nickname: row?.nickname ?? "",
          email: row?.email ?? "",
          sex: row?.sex ?? "",
          phone: row?.phone ?? "",
          status: row?.status ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          updateUserInfo(curData)
            .then(() => {
              message(`用户数据更改成功`, {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(() => {
              done(); // 关闭弹框
            });
        }
        FormRef.validate(valid => {
          if (valid) {
            chores();
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    addDialog({
      title: `分配 ${row.nickname} 用户的角色`,
      props: {
        formInline: {
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          roleid: row?.roleid ?? ""
        }
      },
      width: "400px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline;
        updateUserInfo({ ...curData, id: row.id })
          .then(() => {
            message(`用户数据更改成功`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          })
          .catch(() => {
            done(); // 关闭弹框
          });
      }
    });
  }

  onMounted(async () => {
    onSearch();
    // 角色列表
    roleOptions.value = (await getAllRoleList(toRaw(pagination))).data.records;
    roleOptions.value.forEach(item => {
      item.id = item.id;
      item.name = item.roleName;
    });
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    handleRole,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
